package com.jack006.admin.controller;

import com.jack006.admin.service.AdminUserService;
import com.jack006.api.BaseController;
import com.jack006.api.controller.admin.AdminMngControllerApi;
import com.jack006.exception.GraceException;
import com.jack006.grace.result.GraceJSONResult;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.AdminUser;
import com.jack006.pojo.bo.AdminLoginBO;
import com.jack006.pojo.bo.NewAdminBO;
import com.jack006.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;

/**
 * @Classname AdminMngController
 * @Description admin 管理控制
 * @Date 2021-06-26 16:33
 * @Created by jack
 */
@RestController
public class AdminMngController extends BaseController implements AdminMngControllerApi {

    final static Logger LOGGER = LoggerFactory.getLogger(AdminMngController.class);

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private RestTemplate restTemplate;
//    @Autowired
//    private FaceVerifyUtils faceVerifyUtils;
//    @Autowired
//    private DiscoveryClient discoveryClient;

    @Override
    public GraceJSONResult adminLogin(@Valid AdminLoginBO adminLoginBO,
                             HttpServletRequest request,
                             HttpServletResponse response) {

        // 1. 查询 admin 用户的信息
        AdminUser admin = adminUserService.queryAdminByUserName(adminLoginBO.getUsername());

        // 2. 判断 admin 不为空，如果空则登录失败
        if (admin == null) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }

        // 3. 判断密码是否匹配
        boolean isPwdMatch = BCrypt.checkpw(adminLoginBO.getPassword(),admin.getPassword());
        if (isPwdMatch) {
            doLoginSettings(admin,request,response);
            return GraceJSONResult.ok();
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_NOT_EXIT_ERROR);
        }
    }

    @Override
    public GraceJSONResult adminIsExist(String userName) {
        // 校验 用户名是否存在
        checkAdminExist(userName);
        return  GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult addNewAdmin(@Valid NewAdminBO newAdminBO, HttpServletRequest request, HttpServletResponse response) {

        // 1、base64 不为空，则代表人脸入库，否则用户输入密码和确认密码
        if (StringUtils.isBlank(newAdminBO.getImg64())) {
            if (StringUtils.isBlank(newAdminBO.getPassword()) ||
                    StringUtils.isBlank(newAdminBO.getConfirmPassword())) {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_NULL_ERROR);
            }
        }

        // 2、密码不为空，则必须判断两次密码输入一致
         if(StringUtils.isNotBlank(newAdminBO.getPassword())
                 && !newAdminBO.getPassword().equalsIgnoreCase(newAdminBO.getConfirmPassword())) {
             return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_PASSWORD_ERROR);
         }

         // 3、校验用户名唯一
        checkAdminExist(newAdminBO.getUsername());

         // 4.调用 service 存入 admin 信息
         adminUserService.createAdminUser(newAdminBO);
        return  GraceJSONResult.ok();
    }

    private void checkAdminExist(String userName) {
        AdminUser adminUser = adminUserService.queryAdminByUserName(userName);
        if (adminUser != null) {
            GraceException.display(ResponseStatusEnum.ADMIN_USERNAME_EXIST_ERROR);
        }
    }

    /**
     * 用户 admin 用户登录过后的基本信息使用
     * @param admin
     * @param request
     * @param response
     */
    private void doLoginSettings(AdminUser admin,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        // 保存 token 放到 redis
        String token = UUID.randomUUID().toString();
        redisOperator.set(REDIS_ADMIN_TOKEN+":"+admin.getId(),token);

        // 保存 admin 登录token 和基本信息到 cookie
        setCookieValue(request,response,"atoken",token,COOKIE_MONTH);
        setCookieValue(request,response,"aid",admin.getId(),COOKIE_MONTH);
        setCookieValue(request,response,"aname",admin.getAdminName(),COOKIE_MONTH);
    }

    @Override
    public GraceJSONResult getAdminList(Integer page, Integer pageSize) {
        if (page == null) {
            page = COMMON_START_PAGE;
        }

        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        PagedGridResult gridResult = adminUserService.queryAdminList(page, pageSize);
        return GraceJSONResult.ok(gridResult);
    }


    @Override
    public GraceJSONResult adminLogout(String adminId, HttpServletRequest request, HttpServletResponse response) {

        // 从 redis中删除 admin 会话信息
        redisOperator.del(REDIS_ADMIN_TOKEN+":"+adminId);

        // 从cookie 清理 admin 登录相关信息
        deleteCookie(request,response,"atoken");
        deleteCookie(request,response,"aid");
        deleteCookie(request,response,"aname");

        return GraceJSONResult.ok();
    }

    @Override
    public GraceJSONResult adminFaceLogin(AdminLoginBO adminLoginBO, HttpServletRequest request, HttpServletResponse response) {

        // 0. 判断用户名和人脸信息不为空
        if (StringUtils.isBlank(adminLoginBO.getUsername())) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_ID_IS_NULL_ERROR);
        }

        String tempFace64 = adminLoginBO.getImg64();
        if (StringUtils.isBlank(tempFace64)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }
        // 1. 从数据库查询人脸 faceId
        AdminUser adminUser = adminUserService.queryAdminByUserName(adminLoginBO.getUsername());
        String adminUserFaceId = adminUser.getFaceId();

        // 2. 请求文件服务，获取人脸数据的 base64 数据

        String serviceId = "SERVICE-FILES";
//        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
//        ServiceInstance serviceInstance = instances.get(0);
        // String fileServerUrlExecute = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/fs/readInGridFS?faceId="+adminUserFaceId;

        String fileServerUrlExecute = "http://"+serviceId+"/fs/readInGridFS?faceId="+adminUserFaceId;
        ResponseEntity<GraceJSONResult> responseEntity
                = restTemplate.getForEntity(fileServerUrlExecute, GraceJSONResult.class);
        GraceJSONResult bodyResult = responseEntity.getBody();
        String base64Data = (String) bodyResult.getData();

        // 3. 调用阿里 AI 进行人脸对比识别，判断可信度，从而实现人脸登录
//        boolean isMatch = faceVerifyUtils.faceVerify(FaceVerifyType.BASE64.type, tempFace64, base64Data, 60);
//        if (!isMatch) {
//            return GraceJSONResult.errorCustom(ResponseStatusEnum.FACE_VERIFY_LOGIN_ERROR);
//        }
        // 4. admin 登录后的数据设置，redis 与 cookie
        doLoginSettings(adminUser,request,response);
        return GraceJSONResult.ok();
    }
}
